<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/home/welcome">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色详情</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row :gutter="20">
        <el-col :span="2">
          <el-button type="primary" @click="addflag=true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column prop label type="expand" width="80">
          <template slot-scope="scope">
            <el-row
              :class="['bdtop','pdleft','vencenter']"
              v-for="(item,index) in scope.row.children"
              :key="item.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag>{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <el-row
                  :gutter="20"
                  v-for="item1 in item.children"
                  :key="item1.id"
                  :class="['bdbottom','vencenter']"
                >
                  <el-col :span="6">
                    <el-tag type="success">{{item1.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      @close="removeRight(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="#" width="80"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="180"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="small" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRole(scope.row.id)"
            >删除</el-button>
            <el-button
              size="small"
              type="warning"
              icon="el-icon-setting"
              @click="getRights(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色的对话框 -->
      <el-dialog title="角色信息" :visible.sync="addflag">
        <el-form :model="roledata" label-width="100px" :rules="addFormRules" ref="addrole">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="roledata.roleName" autofocus></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="roledata.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addflag = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限的对话框 -->
      <el-dialog title="权限分配" :visible.sync="rightflag" width="30%">
        <!-- 权限的树形图 -->
        <el-tree
          :data="rightList"
          :props="treeProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="keyidList"
          ref="treeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rightflag = false">取 消</el-button>
          <el-button type="primary" @click="updateRights()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 添加角色信息是否显示
      addflag: false,
      // 权限分配对话框是否显示
      rightflag: false,
      //用于获取所有角色信息
      roleList: [],
      // 所有的权限信息
      rightList: [],
      // 树形图的属性值
      treeProps: {
        label: "authName",
        children: "children"
      },
      // 默认选中的keyid数组
      keyidList: [],
      // 现在正在修改权限的id
      curRoleId: "",
      // 添加角色信息
      roledata: {
        roleName: "",
        roleDesc: ""
      },
      // 添加角色信息的验证规则
      addFormRules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 获取角色信息列表
    getRole() {
      this.axios.get("roles").then(res => {
        this.roleList = res.data;
        console.log(this.roleList);
      });
    },
    // 添加角色的信息
    addRole() {
      this.$refs.addrole.validate(valid => {
        if (!valid) return;
        this.axios.post("roles", this.roledata).then(res => {
          console.log(res);

          if (res.meta.status == 201) {
            this.$message.success({
              message: "添加角色成功",
              duration: 1000
            });
            //  消除添加框
            this.addflag = false;
            // 并重新获取数据
            this.getRole();
          } else {
            this.$message.error({
              message: "添加角色失败",
              duration: 1000
            });
          }
        });
      });
    },
    // 删除角色的信息
    deleteRole(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 发送请求去删除数据
          this.axios.delete("roles/" + id).then(res => {
            if (res.meta.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              // 重新获取数据
              this.getRole();
            } else {
              this.$message.error({
                message: "删除失败",
                duration: 1000
              });
            }
          });
        })
        .catch(() => {});
    },
    // 移除用户的某个权限
    removeRight(item, rid) {
      this.$confirm("此操作将删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 发送请求去删除数据
          this.axios.delete("roles/" + item.id + "/rights/" + rid).then(res => {
            if (res.meta.status == 200) {
              this.$message({
                type: "success",
                message: "删除权限成功!"
              });
              // 重新获取数据
              // 不全部重新获取,防止全部重新渲染
              item.children = res.data;
            } else {
              this.$message.error({
                message: "删除权限失败",
                duration: 1000
              });
            }
          });
        })
        .catch(() => {});
    },
    // 获取所有权限列表
    getRights(role) {
      this.axios.get("/rights/tree").then(res => {
        if (res.meta.status != 200)
          return this.$message.error({
            message: "获取权限失败",
            duration: 1000
          });
        // 显示对话框
        this.rightflag = true;
        // 更新数据
        this.rightList = res.data;
        // 重置默认选中的数组  防止下次点击时复用
        this.keyidList.length = 0;
        // 获取当前角色的权限  更新树形图选中的数组
        this.getLeafKeys(role, this.keyidList);
        // 同时声明正在操作的角色id
        this.curRoleId = role.id;
        console.log(res.data);
      });
    },
    //利用递归获取  角色的权限id
    getLeafKeys(node, arr) {
      // 如果node节点不包含children属性则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr);
      });
    },
    //更新用户的权限
    updateRights() {
      // 获取树形图中被选中和被半选中的权限id
      let rightArr = this.$refs.treeRef
        .getCheckedKeys()
        .concat(this.$refs.treeRef.getHalfCheckedKeys());
      console.log(rightArr);
      const idstr = rightArr.join(",");
      console.log(this.curRoleId, idstr);

      this.axios
        .post("roles/" + this.curRoleId + "/rights", { rids: idstr })
        .then(res => {
          console.log(res);
          if (res.meta.status != 200)
            return this.$message.error({
              message: "更新权限失败",
              duration: 1000
            });
          this.$message.success({
            message: "更新权限成功",
            duration: 1000
          });
          // 消失对话框

          this.rightflag = false;
          this.getRole();
        });
    }
  },
  mounted() {
    this.getRole();
  }
};
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.pdleft {
  padding-left: 80px;
}
.vencenter {
  display: flex;
  align-items: center;
}
</style>
